from django.shortcuts import render, redirect, reverse
from goods.models import IndexPromote, GoodsBanner, Goods, GoodsType
from order.models import OrderInfo, OrderGoods
from django.views.generic import View
from django.core.cache import cache
from django_redis import get_redis_connection
from django.core.paginator import Paginator


def index(request):
    # 判断是否有缓存
    context = cache.get('page_cache')
    if context is None:
        # 促销
        promote = IndexPromote.objects.all().order_by('id')
        # 轮播
        slider = GoodsBanner.objects.all().order_by('-id')

        # 精品推荐
        recommend = Goods.objects.all().order_by('-id')[:6]

        # 笔记本/游戏本
        laptop = GoodsType.objects.get(name='笔记本') # 注意用get
        laptop = laptop.goods_set.all().order_by('-id')[:6]

        # Desktop
        desktop = GoodsType.objects.get(name='台式机').goods_set.all().order_by('-id')[:6]

        # 配件
        parts = GoodsType.objects.get(name='配件').goods_set.all()[:3]

        context = {
            'promote': promote,
            'slider': slider,
            'recommend': recommend,
            'laptop': laptop,
            'desktop': desktop,
            'parts': parts,
            'goods_type': '首页'
            }
        # 设置缓存
        cache.set('page_cache', context, 3600)
    # 判断用户是否登录
    user = request.user
    cart_count = 0
    if user.is_authenticated:
        conn = get_redis_connection('default')
        cart_key = 'cart_%d'%user.id
        cart_count = conn.hlen(cart_key)
        # 更新字典可以用update
    context.update(cart_count=cart_count)
    return render(request, 'index.html', context)


# 商品分类页
class GoodsSort(View):
    def get(self, request, goods_type, page_num):
        try:
            computer = GoodsType.objects.get(name=goods_type).goods_set.all()
        except computer.DoesNotExist:
            return redirect(reverse('goods'))
        sort = request.GET.get('sort')
        if sort == 'Lprice':
            computer = computer.order_by('price')
        elif sort == 'Tprice':
            computer = computer.order_by('-price')

        pagenator = Paginator(computer, 6)

        try:
            page_num = int(page_num)
        except:
            page_num = 1

        num_page = pagenator.num_pages
        if page_num > num_page:
            page_num = 1
        page_result = pagenator.page(page_num)

        if num_page < 5:
            pages = range(1, num_page+1)
        elif page_num < 3:
            pages = range(1, 6)
        elif num_page - page_num < 2:
            pages = range(page_num-4, page_num+1)
        else:
            pages = range(page_num - 2, page_num + 3)




        user = request.user
        cart_count = 0
        if user.is_authenticated:
            conn = get_redis_connection('default')
            cart_key = 'cart_%d' %user.id
            cart_count = conn.hlen(cart_key)
        context = {
            'computer': computer,
            'goods_type': goods_type,
            'cart_count': cart_count,
            'page_goods': page_result,
            'sort': sort,
            'pages': pages
        }
        return render(request, 'goods_sort.html', context)


class GoodsDetail(View):
    def get(self, request, goods_id):
        try:
            goods = Goods.objects.get(pk=goods_id)
        except goods.DoesNotExist:
            return redirect(reverse('goods'))

        relate = Goods.objects.filter(type=goods.type)[0:5]
        goods_orders = goods.ordergoods_set.all()

        cart_count = 0
        user = request.user
        if user.is_authenticated:
            conn = get_redis_connection('default')
            cart_key = 'cart_%d' % user.id
            cart_count = conn.hlen(cart_key)
            # 添加用户的历史记录
            conn = get_redis_connection('default')
            history_key = 'history_%d' % user.id
            # 移除列表中的goods_id
            conn.lrem(history_key, 0, goods_id)
            # goods_id插入到列表的左侧
            conn.lpush(history_key, goods_id)
            conn.ltrim(history_key, 0, 5)


        context = {
            'goods': goods,
            'relate': relate,
            'cart_count': cart_count,
            'goods_orders': goods_orders
            }
        return render(request, 'detail.html', context)



